/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.config.refresh.smart;

import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;

/**
 * 扩展的GenericBeanDefinition，支持bean刷新
 *
 * @auther ebert_chan
 */
@SuppressWarnings("serial")
public class SmartBeanDefinition extends GenericBeanDefinition {

    /**
     * 刷新key
     */
    private String refreshKey;

    /**
     * Create a new GenericBeanDefinition as deep copy of the given bean definition.
     *
     * @param refreshKey the key prefix
     * @param original   the original bean definition to copy from
     */
    public SmartBeanDefinition(String refreshKey, BeanDefinition original) {
        super(original);
        this.setRefreshKey(refreshKey);
        this.setScope(SmartScope.SCOPE_NAME);
    }

    /**
     * Create a new GenericBeanDefinition
     *
     * @param refreshKey the key prefix
     */
    public SmartBeanDefinition(String refreshKey) {
        super();
        this.setScope(SmartScope.SCOPE_NAME);
    }


    /**
     * 注册BeanDefinition，自动生成代理bean
     *
     * @param registry BeanDefinitionRegistry
     * @param beanName
     */
    public void registerBeanDefinition(BeanDefinitionRegistry registry, String beanName) {
        BeanDefinitionHolder scopedBeanDefinitionHolder = new BeanDefinitionHolder(this, beanName);
        BeanDefinitionHolder proxyDefinitionHolder = ScopedProxyUtils.createScopedProxy(scopedBeanDefinitionHolder, registry, true);
        registry.registerBeanDefinition(proxyDefinitionHolder.getBeanName(), proxyDefinitionHolder.getBeanDefinition());
    }

    public String getRefreshKey() {
        return refreshKey;
    }

    public void setRefreshKey(String refreshKey) {
        this.refreshKey = refreshKey;
    }

}
